package crypto

import (
	"bytes"
	"fmt"
	"golang.org/x/crypto/bcrypt"
)

// PasswordHash 生成BCrypt哈希
func PasswordHash(password string, cost int) string {
	if cost < bcrypt.MinCost || cost > bcrypt.MaxCost {
		cost = bcrypt.DefaultCost
	}
	hashedBytes, err := bcrypt.GenerateFromPassword([]byte(password), cost)
	if err != nil {
		panic(err)
	}
	// 将Go的$2a$版本标识符替换为PHP的$2y$
	hashedStr := string(hashedBytes)
	if bytes.HasPrefix([]byte(hashedStr), []byte("$2a$")) {
		hashedStr = fmt.Sprintf("%v%v", "$2y$", hashedStr[4:])
	}
	return hashedStr
}

// PasswordVerify 验证密码是否匹配哈希
func PasswordVerify(password, hashed string) bool {
	// 允许$2y$前缀被Go识别
	adjusted := []byte(hashed)
	if bytes.HasPrefix(adjusted, []byte("$2y$")) {
		adStr := fmt.Sprintf("%v%v", "$2a$", string(adjusted[4:]))
		adjusted = []byte(adStr)
	}
	err := bcrypt.CompareHashAndPassword(adjusted, []byte(password))
	return err == nil
}
